package com.lagou.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lagou.rpc.RpcRequest;
import com.lagou.service.UserServiceImpl;
import com.lagou.utils.SpringContextHolder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 自定义的业务处理器
 */
@Service
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
         //1.判断当前的请求是否符合规则

        RpcRequest rpcRequest = (RpcRequest) msg;
        String className = rpcRequest.getClassName();
        Class<?> cl = Class.forName(className);
        String simpleName = cl.getSimpleName();
        Object o = SpringContextHolder.getBean(simpleName);
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Method declaredMethod = cl.getDeclaredMethod(methodName, parameterTypes);
        declaredMethod.setAccessible(true);
        Object args[] = rpcRequest.getParameters();
        String result = (String) declaredMethod.invoke(o,args);
        ctx.writeAndFlush(result);
    }
}
